import { View, Slider, ScrollView, Text } from "@tarojs/components";
import {
  ConfigProvider,
  Tabs,
  Video,
  Cell,
  Button,
  Swiper,
  SwiperItem,
  Image,
  Picker,
} from "@nutui/nutui-react-taro";
import { ArrowRight, Loading1 } from "@nutui/icons-react-taro";
import { useState, useEffect, useRef } from "react";
import Taro, {
  useRouter,
  downloadFile,
  useShareAppMessage,
  getVideoInfo,
} from "@tarojs/taro";
import { wxDetail } from "@/api/course";
import { isJumpToCourseDetail, getNoteDetail } from "@/api/note";

const Note = ({
  isNoteDetail = false,
  setOpusUid,
}: {
  isNoteDetail?: boolean;
  setOpusUid?: (opusUid: string) => void;
}) => {
  const { params } = useRouter();
  const [isRole, setIsRole] = useState(true);
  const [TabValue, setTabValue] = useState(0);
  const [opusName, setOpusName] = useState("");
  const [bindName, setBindName] = useState("");
  const [isAudio, setIsAudio] = useState(false);
  const [isHidden, setIsHidden] = useState(false);
  const [detail, setDetail] = useState<any>(null);
  const [imageList, setImageList] = useState<any[]>([]);
  const [profile, setProfile] = useState<any>(null);
  const [ratio, setRatio] = useState("529/707");
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const [progressValue, setProgressValue] = useState(0);
  const [audioManager, setAudioManager] = useState<any>(null);
  const [isAudioPlaying, setIsAudioPlaying] = useState(false);
  const [isShowAudio, setIsShowAudio] = useState(false);
  //播放 loading
  const [isPlayLoading, setIsPlayLoading] = useState(false);
  // 音频倍速
  const [playbackRate, setPlaybackRate] = useState(1.0);

  const queryRef = useRef("");
  const getList = async () => {
    Taro.showLoading();
    if (isNoteDetail) {
      const result = await isJumpToCourseDetail(params.uid || queryRef.current);
      if (result.data) {
        Taro.redirectTo({
          url: `/pages/profile/index?bindUid=${result.data}`,
        });
        return false;
      }
      const res = await getNoteDetail(params.uid || queryRef.current);
      Taro.hideLoading();
      if (res.code === 0) {
        setDetail(res?.data);
        const data = res?.data?.executeResult;
        setBindName(data?.copyWriting?.title);
        setProfile(data?.resource);
        setDetail(res?.data);
        setImageList(data?.imageList || []);
        setIsShowAudio(!!data?.resource?.completeAudioUrl);
        setOpusName("魔法学");
        setIsHidden(true);
        if (res?.data?.executeResult?.video?.completeVideoUrl) {
          downloadFile({
            url: res?.data?.executeResult?.video?.completeVideoUrl,
            success: (res) => {
              getVideoInfo({
                src: res.tempFilePath,
                success: (res) => {
                  setRatio(`${res.width}/${res.height}`);
                },
              });
            },
          });
        }
      }
    } else {
      try {
        const res = await wxDetail(params.bindUid || queryRef.current);
        Taro.hideLoading();
        if (res.code === 0) {
          setOpusUid?.(res?.data?.opusUid);
          setOpusName(res?.data?.opusName);
          setBindName(res?.data?.bindName);
          setProfile(res?.data?.contentResource?.resource);
          setDetail(res?.data?.contentRespVO);
          setImageList(
            res?.data?.contentRespVO?.executeResult?.imageList || []
          );
          setIsAudio(res?.data?.autoJump);
          setIsHidden(res?.data?.resourceDownloadAllowed);
          setIsShowAudio(
            res?.data?.contentRespVO?.executeResult?.video?.completeAudioUrl
          );
          if (
            res?.data?.contentRespVO?.executeResult?.video?.completeVideoUrl
          ) {
            downloadFile({
              url: res?.data?.contentRespVO?.executeResult?.video
                ?.completeVideoUrl,
              success: (res) => {
                getVideoInfo({
                  src: res.tempFilePath,
                  success: (res) => {
                    setRatio(`${res.width}/${res.height}`);
                  },
                });
              },
            });
          }
        } else if (res.code === 2000700002) {
          setIsRole(false);
          Taro.showToast({
            icon: "none",
            title: "暂无权限访问，即将跳转至课程详情",
          });
          setTimeout(() => {
            Taro.redirectTo({
              url: `/pages/course-detail/index?opusUid=${res.data}`,
            });
          }, 2000);
        }
      } catch (error) {
        Taro.hideLoading();
      }
    }
  };
  Taro.useLoad((options) => {
    if (options.hasOwnProperty("q") && options.q) {
      queryRef.current = decodeURIComponent(options.q)?.split("=")[1];
      console.log(queryRef.current, "queryRef.current123");
    }
  });
  Taro.useDidShow(() => {
    console.log(queryRef.current, "queryRef.current");
    getList();
  });
  useShareAppMessage(() => {
    return {
      title: "短文学习",
      path: `/pages/profile/index?bindUid=${params.bindUid}`,
    };
  });
  useEffect(() => {
    if (detail?.executeResult?.video?.completeAudioUrl) {
      const manager = Taro.getBackgroundAudioManager();
      // 监听音频加载完成
      manager.onCanplay(() => {
        setDuration(manager.duration || 0);
      });
      // 监听播放进度
      manager.onTimeUpdate(() => {
        const currentTime = manager.currentTime;
        const duration = manager.duration;
        setCurrentTime(currentTime);
        setDuration(duration);
        setProgressValue((currentTime / duration) * 100);
      });

      //手动关闭后台播放
      manager.onStop(() => {
        manager.stop();
        setIsAudioPlaying(false);
        setCurrentTime(0);
        setProgressValue(0);
      });

      manager.onPlay(() => {
        setIsPlayLoading(false);
        setIsAudioPlaying(true);
      });

      manager.onPause(() => {
        setIsAudioPlaying(false);
      });

      // 监听播放结束
      manager.onEnded(() => {
        setIsAudioPlaying(false);
        setCurrentTime(0);
        setProgressValue(0);
      });
      // 设置默认倍速
      manager.playbackRate = playbackRate;
      setAudioManager(manager);
      if (isAudio) {
        setTabValue(1);
        playSetting(manager);
      }
      return () => {
        manager.stop();
      };
    }
  }, [detail]);

  // 当倍速改变时，同步更新 audioManager
  useEffect(() => {
    if (audioManager) {
      audioManager.playbackRate = playbackRate;
    }
  }, [playbackRate, audioManager]);
  const playSetting = (manager?: any) => {
    setIsPlayLoading(true);

    const target = manager || audioManager;
    if (!target) return;

    target.title = `${bindName}.mp3`;
    target.singer = opusName;
    target.coverImgUrl = imageList?.[0]?.url;
    target.src = detail?.executeResult?.video?.completeAudioUrl;
    target.play();
  };
  // 格式化时间
  const formatTime = (time: number) => {
    const minutes = Math.floor(time / 60);
    const seconds = Math.floor(time % 60);
    return `${minutes?.toString()?.padStart(2, "0")}:${seconds
      ?.toString()
      ?.padStart(2, "0")}`;
  };
  const [visible, setVisible] = useState(false);
  return (
    <View className="bg-[#F5F5F5] min-h-full my-page">
      {isRole ? (
        <ConfigProvider
          theme={{
            nutuiTabsTabpanePadding: "0 16rpx 16rpx 16rpx",
            nutuiTabsTitlesBackgroundColor: "#fff",
          }}
        >
          <Tabs
            activeType="button"
            align="left"
            value={TabValue}
            onChange={(value) => {
              setTabValue(Number(value));
              if (value === 0) {
                audioManager?.pause();
              } else if (value === 1) {
                Taro.createVideoContext("video").pause();
              }
            }}
          >
            {isNoteDetail ? (
              <Tabs.TabPane
                value={0}
                className="h-[calc(100vh-60px)]"
                title="笔记详情"
              >
                <ScrollView scrollY className="bg-white rounded-lg p-2 h-full">
                  {detail?.executeResult?.video?.completeVideoUrl ||
                  (detail?.executeResult?.videoList &&
                    detail?.executeResult?.videoList[0]?.url) ? (
                    <Video
                      id="video"
                      style={{
                        width: "100%",
                        height: "auto",
                        aspectRatio: ratio,
                      }}
                      source={{
                        src:
                          detail?.executeResult?.video?.completeVideoUrl ||
                          (detail?.executeResult?.videoList &&
                            detail?.executeResult?.videoList[0]?.url),
                        type: "video",
                      }}
                      options={{
                        poster: imageList[0]?.url,
                      }}
                    />
                  ) : (
                    <Swiper
                      style={{ touchAction: "pan-y", overflow: "hidden" }}
                      circular
                      indicatorDots
                      indicatorActiveColor="#673ab7"
                      height="478"
                    >
                      {imageList?.map((item, index) => (
                        <SwiperItem
                          className="flex justify-center"
                          key={item.uuid}
                        >
                          <Image
                            onClick={(e) => {
                              e.stopPropagation();
                              if (imageList && imageList.length > 0) {
                                const urls = imageList.map((item) => item.url);
                                Taro.previewImage({
                                  urls,
                                  current: urls[index],
                                });
                              }
                            }}
                            catch-move="false"
                            mode="widthFix"
                            className="!flex justify-center"
                            src={item.url}
                          />
                        </SwiperItem>
                      ))}
                    </Swiper>
                  )}
                  <View className="text-base font-semibold mt-4 mb-2">
                    {detail?.executeResult?.copyWriting?.title}
                  </View>
                  <View
                    className={`text-sm text-gray-500 whitespace-pre-wrap ${
                      detail?.executeResult?.copyWriting?.tagList?.length > 0
                        ? "pb-0"
                        : "pb-[150rpx]"
                    }`}
                  >
                    {detail?.executeResult?.copyWriting?.content}
                  </View>
                  <View className={`text-[#673ab7] text-xs mt-4`}>
                    {detail?.executeResult?.copyWriting?.tagList?.map(
                      (item) => (
                        <Text key={item} className="mr-2">
                          #{item}
                        </Text>
                      )
                    ) || null}
                  </View>
                </ScrollView>
              </Tabs.TabPane>
            ) : (
              <Tabs.TabPane
                value={0}
                className="h-[calc(100vh-131px)]"
                title="视频"
              >
                {bindName && (
                  <View className="text-[45rpx] mb-2">{bindName}</View>
                )}
                <View
                  onClick={() => {
                    Taro.navigateBack();
                  }}
                  className="text-xs text-black/60 mb-2 flex items-center"
                >
                  来自：{opusName}
                  <ArrowRight size="14" />
                </View>
                {detail?.executeResult?.video?.completeVideoUrl ? (
                  <Video
                    id="video"
                    style={{
                      width: "100%",
                      height: "auto",
                      aspectRatio: ratio,
                    }}
                    source={{
                      type: "video",
                      src: detail?.executeResult?.video?.completeVideoUrl,
                    }}
                  />
                ) : (
                  <Swiper height={"100%"} defaultValue={1} autoPlay indicator>
                    {imageList?.map((item, index) => (
                      <SwiperItem key={item.url}>
                        <Image
                          width="100%"
                          mode="widthFix"
                          src={item.url}
                          onClick={(e) => {
                            e.stopPropagation();
                            if (imageList && imageList.length > 0) {
                              const urls = imageList.map((item) => item.url);
                              Taro.previewImage({
                                urls,
                                current: urls[index],
                              });
                            }
                          }}
                        />
                      </SwiperItem>
                    ))}
                  </Swiper>
                )}
              </Tabs.TabPane>
            )}
            {isShowAudio && (
              <Tabs.TabPane
                className="h-[calc(100vh-131px)] relative overflow-hidden"
                title="音频"
              >
                <View className="max-h-full">
                  {bindName && (
                    <View className="text-[45rpx] mb-2">{bindName}</View>
                  )}
                  <Image
                    // className="mb-[225rpx]"
                    width="100%"
                    height="auto"
                    mode="widthFix"
                    src={imageList[0]?.url}
                  />
                </View>
                <View className="w-full p-2 bg-white rounded-lg">
                  <View className="flex items-center">
                    <Slider
                      className="w-full flex-1"
                      showValue={false}
                      blockSize={12}
                      value={progressValue}
                      onChange={(e) => {
                        const newValue = e.detail.value;
                        setProgressValue(newValue);
                        if (audioManager) {
                          const newTime = (newValue / 100) * duration;
                          audioManager.seek(newTime);
                          // 确保音频继续播放
                          audioManager.play();
                        }
                      }}
                    />
                    <View className="text-xs text-black/60">
                      {formatTime(currentTime) + "/" + formatTime(duration)}
                    </View>
                  </View>
                  <View className="flex justify-center items-center gap-8 relative">
                    <Image
                      onClick={() => {
                        if (audioManager) {
                          // 计算新的时间（当前时间 - 5秒）
                          const newTime = Math.max(0, currentTime - 5);
                          // 更新进度条
                          setCurrentTime(newTime);
                          setProgressValue((newTime / duration) * 100);
                          // 跳转到新位置
                          audioManager.seek(newTime);
                        }
                      }}
                      src={require("../../../assets/profile/left.svg")}
                      width="50rpx"
                      height="50rpx"
                    />
                    <View
                      onClick={() => {
                        if (!audioManager?.src || duration === 0) {
                          playSetting();
                        } else if (audioManager?.paused) {
                          setIsPlayLoading(true);
                          audioManager?.play();
                        } else {
                          audioManager?.pause();
                        }
                      }}
                      className="w-[80rpx] h-[80rpx] rounded-full bg-[#673ab7] flex items-center justify-center"
                    >
                      {isPlayLoading ? (
                        <Loading1 color="white" />
                      ) : isAudioPlaying ? (
                        <Image
                          src={require("../../../assets/profile/pause.svg")}
                          loading={false}
                          width="50rpx"
                          height="50rpx"
                        />
                      ) : (
                        <Image
                          src={require("../../../assets/profile/play.svg")}
                          loading={false}
                          width="50rpx"
                          height="50rpx"
                        />
                      )}
                    </View>
                    <Image
                      onClick={() => {
                        if (audioManager) {
                          // 计算新的时间（当前时间 + 5秒）
                          const newTime = Math.min(duration, currentTime + 5);
                          // 更新进度条
                          setCurrentTime(newTime);
                          setProgressValue((newTime / duration) * 100);
                          // 跳转到新位置
                          audioManager.seek(newTime);
                        }
                      }}
                      width="50rpx"
                      height="50rpx"
                      src={require("../../../assets/profile/right.svg")}
                    />
                    <View
                      onClick={() => setVisible(true)}
                      className="absolute right-0 text-xs border-[1px] border-solid border-black rounded-[8px] p-1"
                    >
                      {playbackRate}倍速
                    </View>
                  </View>
                </View>
              </Tabs.TabPane>
            )}
            {isHidden && !isNoteDetail && (
              <Tabs.TabPane title="资料下载">
                <Cell
                  title={`${bindName}.MP3`}
                  extra={
                    <Button
                      size="small"
                      disabled={!profile?.completeAudioUrl}
                      onClick={() => {
                        downloadFile({
                          url: profile?.completeAudioUrl,
                          success: (res) => {
                            Taro.shareFileMessage({
                              filePath: res.tempFilePath,
                              fileName: bindName + ".mp3",
                              fail: (err) => {
                                Taro.showToast({
                                  icon: "none",
                                  title: err.errMsg,
                                });
                              },
                            });
                          },
                        });
                      }}
                    >
                      下载并发送
                    </Button>
                  }
                />
                <Cell
                  title={`${bindName}.MP4`}
                  extra={
                    <Button
                      size="small"
                      disabled={!profile?.completeVideoUrl}
                      onClick={() => {
                        downloadFile({
                          url: profile?.completeVideoUrl,
                          success: (res) => {
                            Taro.shareVideoMessage({
                              videoPath: res.tempFilePath,
                            });
                          },
                        });
                      }}
                    >
                      下载并发送
                    </Button>
                  }
                />
                <Cell
                  title={`${bindName}.PDF`}
                  extra={
                    <Button
                      size="small"
                      disabled={!profile?.pdfUrl}
                      onClick={() => {
                        downloadFile({
                          url: profile?.pdfUrl,
                          success: (res) => {
                            Taro.shareFileMessage({
                              filePath: res.tempFilePath,
                              fileName: bindName + ".pdf",
                            });
                          },
                        });
                      }}
                    >
                      下载并发送
                    </Button>
                  }
                />
              </Tabs.TabPane>
            )}
          </Tabs>
        </ConfigProvider>
      ) : (
        <Image
          className="!flex items-center justify-center"
          width="100%"
          height="100vh"
          mode="widthFix"
          src={require("../../../assets/profile/403.svg")}
        />
      )}
      <Picker
        title="请选择语速(倍速)"
        visible={visible}
        options={[
          { text: "0.6倍速", value: 0.6 },
          { text: "0.8倍速", value: 0.8 },
          { text: "1.0倍速", value: 1 },
          { text: "1.2倍速", value: 1.2 },
          { text: "1.4倍速", value: 1.4 },
          { text: "1.6倍速", value: 1.6 },
          { text: "1.8倍速", value: 1.8 },
          { text: "2.0倍速", value: 2 },
        ]}
        onConfirm={(e) => {
          const selectedRate = Number(e[0]?.value) || 1.0;
          setPlaybackRate(selectedRate);
          if (audioManager) {
            audioManager.playbackRate = selectedRate;
          }
          setVisible(false);
        }}
        onClose={() => setVisible(false)}
      />
    </View>
  );
};

export default Note;
